package com.unibuy.smartdevice.ui.devs.electric;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.unibuy.smartdevice.FragmentAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.database.SlotsDao;
import com.unibuy.smartdevice.databinding.RecyclerElectricBuyListBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.structure.BuyStructure;
import com.unibuy.smartdevice.structure.MarketingPlanStructure;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.dialog.BuyDialog;
import com.unibuy.smartdevice.ui.dialog.CloseAccessCodeDialog;
import com.unibuy.smartdevice.ui.dialog.MarketingPlanDialog;
import com.unibuy.smartdevice.ui.tools.ImageGlide;

import org.json.JSONException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class RecyclerElectricBuyListAdpter extends RecyclerView.Adapter<RecyclerElectricBuyListAdpter.ViewHolder> {
    private Logs logs;
    private Context context;
    private final List<SlotStructure> slotList;
    private FragmentAbstract fragment;
    private HandlerMain handlerMain;

    public RecyclerElectricBuyListAdpter(FragmentAbstract fragment, List<SlotStructure> slotList, HandlerMain handlerMain) {
        this.logs = new Logs(this.getClass());
        this.context = fragment.getContext();
        this.slotList = slotList;
        this.fragment = fragment;
        this.handlerMain = handlerMain;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        RecyclerElectricBuyListBinding binding;

        public ViewHolder(@NonNull RecyclerElectricBuyListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 使用 ViewBinding 來綁定佈局
        RecyclerElectricBuyListBinding binding = RecyclerElectricBuyListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);

        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        SlotStructure slot = slotList.get(position);
        logs.info("recycler slot:" + slot.toString());

        String urlString = slot.getProduct().getProductImg();
        try {
            new ImageGlide(context).fileload(urlString, holder.binding.imageProductPicture);
        } catch (LogsEmptyException e) {
            this.logs.warning(e);
        }
        holder.binding.textSlot.setText(String.format("%03d", slot.getSlot()));
        holder.binding.textProductName.setText(slot.getProduct().getProductName());

        int machinePrice = slot.getProduct().getMachinePrice();
        int sellingPrice = slot.getProduct().getSellingPrice();
        int memberPrice = slot.getProduct().getMemberPrice();
        int slotUpperLimit = slot.getProduct().getSlotUpperLimit();
        int count = 1;
        boolean isLock = slot.isLock();

        int price = machinePrice > 0? machinePrice: sellingPrice;

        holder.binding.textPrice.setText("NT$ "+price);

        holder.binding.mask.setVisibility(View.GONE);
        holder.binding.textMask.setText("");

        if (isLock) {
            holder.binding.mask.setVisibility(View.VISIBLE);
            holder.binding.textMask.setText("暫停販售");
        }

        if (count > 0 && !isLock) {
            holder.binding.imageProductPicture.setOnClickListener(new ImageProductPictureOnClickListener(position));
        } else {
            holder.binding.imageProductPicture.setOnClickListener(null);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String timeExpired = "";
        String remainingTime = "";

        if (slot.getOtherData().has("timeExpired")) {
            try {
                timeExpired = slot.getOtherData().getString("timeExpired");
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            timeExpired = timeExpired + " 到期";

            Date now = new Date();
            Date timeEpiredDate = new Date();
            if (slot.getOtherData().has("timeExpired")) {
                try {
                    timeEpiredDate = sdf.parse(slot.getOtherData().getString("timeExpired"));
                } catch (JSONException | ParseException e) {
                    logs.warning(e);
                }
            }
            long diffInMillis = timeEpiredDate.getTime() - now.getTime();

            long diffInSeconds = diffInMillis / 1000; // 總秒數
            int hours = (int) (diffInSeconds / 3600);        // 小時
            int minutes = (int) ((diffInSeconds % 3600) / 60); // 剩下的分鐘
            int seconds = (int) (diffInSeconds % 60);          // 剩下的秒數

            remainingTime = String.format("%02d", hours) + "時: " + String.format("%02d", minutes) + "分";
        } else {
            timeExpired = "未開桌";
            remainingTime = "00時:00分";
        }

        remainingTime = "剩餘 " + remainingTime;

        holder.binding.textTimeExpired.setText(timeExpired);
        holder.binding.textRemainingTime.setText(remainingTime);

        holder.binding.textRemainingTime.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                MyApp.getInstance().setCloseSlot(slot.getSlot());
                new CloseAccessCodeDialog(context, handlerMain).show();
                return true;
            }
        });
    }

    private void saveData() {
        SlotsDao slotsDao = new SlotsDao(context);
        slotsDao.deleteAll();
        slotsDao.insertAll(MyApp.getInstance().getSlotMap());
        slotsDao.close();
        logs.info("save count:"+ MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).size());
    }

    @Override
    public int getItemCount() {
        return slotList.size();
    }

    public void addSlotData(SlotStructure slotStructure) {
        slotList.add(slotStructure);
        notifyItemInserted(slotList.size() - 1);
    }

    public class ImageProductPictureOnClickListener implements View.OnClickListener {
        private int position;

        public ImageProductPictureOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            SlotStructure slotProduct = slotList.get(position);
            if (slotProduct.isLock()) return;
            if (MyApp.getInstance().isShowDialog) return;

            logs.info("marketingPlan:" + slotProduct.getProduct().getMarketingPlan());

            MyApp.getInstance().getMarketingPlanList().clear();

            MarketingPlanStructure marketingPlanStructure = new MarketingPlanStructure(SlotField.ELECTRIC.getField(), slotProduct.getSlot(), slotProduct.getProduct(), slotProduct.getCount());
            MyApp.getInstance().getMarketingPlanList().add(marketingPlanStructure);

            if (!slotProduct.getProduct().getMarketingPlan().isEmpty()) {
                String[] productIds = slotProduct.getProduct().getMarketingPlan().replaceAll(";$", "").split(";");
                for (String productId: productIds) {
                    ProductStructure marketingPlanProduct = null;
                    for (ProductStructure productData: MyApp.getInstance().getProductList()) {
                        if (productData.getProductID().equals(productId)) {
                            marketingPlanProduct = productData;
                        }
                    }

                    if (marketingPlanProduct != null) {
                        logs.info(marketingPlanProduct.toString());
                        marketingPlanStructure = new MarketingPlanStructure(SlotField.ELECTRIC.getField(), slotProduct.getSlot(), marketingPlanProduct, slotProduct.getCount());
                        marketingPlanStructure.setMarketingPlan(true);
                        MyApp.getInstance().getMarketingPlanList().add(marketingPlanStructure);
                    }
                }
            }

            if (MyApp.getInstance().getMarketingPlanList().size() <= 1) {
                boolean pass = true;
                for (int index = 0; index < MyApp.getInstance().getBuyList().size(); index++) {
                    BuyStructure buyData = MyApp.getInstance().getBuyList().get(index);
                    if (buyData.getField() == slotProduct.getField() && buyData.getSlot() == slotProduct.getSlot()) {
                        pass = false;
                        int count = buyData.getCount();
                        buyData.setCount(count+1);
                    }
                }

                if (pass) {
                    BuyStructure buyProduct = new BuyStructure(slotProduct.getField(), slotProduct.getSlot(), slotProduct.getProduct(), 1);
                    MyApp.getInstance().getBuyList().add(buyProduct);
                }

                fragment.getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
                new BuyDialog(context, fragment.getSrcHandlerMain()).show();
            } else {
                fragment.getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.STOP_COUNTDOWN.getOption(), "stop countdown");
                new MarketingPlanDialog(context, fragment.getSrcHandlerMain()).show();
            }
        }
    }
}
